using System;
using System.Collections.Generic;
using CGF;
using LitJson;

public static class Network
{
    public class Res
    {
        public bool success;
        public JsonData jsonData;
    }

    public class CustomPopupMsgs
    {
        public string msg;
        public Action onClose;
    }

    public static async CTask<Res> Get(string url, bool showLoading = true, bool popupError = true, Dictionary<string, CustomPopupMsgs> customPopupMsgs = null)
    {
        if (!url.StartsWith("http"))
        {
            url = Config.Get.APIBaseUrl + url;
        }
        if (showLoading) Wait.Open();
        Dictionary<string, string> header = string.IsNullOrEmpty(UserInfo.Token) ? null : new Dictionary<string, string>()
        {
            { "Authorization", $"Bearer {UserInfo.Token}" }
        };
        HttpRes res = await HttpHelper.Get(url, header);
        if (showLoading) Wait.Close();
        return OnRes(res, popupError, customPopupMsgs);
    }

    public static async CTask<Res> Post(string url, JsonData data, bool showLoading = true, bool popupError = true, Dictionary<string, CustomPopupMsgs> customPopupMsgs = null, int timeoutSeconds = 20)
    {
        if (!url.StartsWith("http"))
        {
            url = Config.Get.APIBaseUrl + url;
        }

        if (showLoading) Wait.Open();
        Dictionary<string, string> header = string.IsNullOrEmpty(UserInfo.Token) ? null : new Dictionary<string, string>()
        {
            { "Authorization", $"Bearer {UserInfo.Token}" }
        };
        HttpRes res = await HttpHelper.PostJson(url, data, header, timeoutSeconds);
        if (showLoading) Wait.Close();
        return OnRes(res, popupError, customPopupMsgs);
    }

    public static async CTask<Res> Put(string url, JsonData data, bool showLoading = true, bool popupError = true, Dictionary<string, CustomPopupMsgs> customPopupMsgs = null, int timeoutSeconds = 20)
    {
        if (!url.StartsWith("http"))
        {
            url = Config.Get.APIBaseUrl + url;
        }

        if (showLoading) Wait.Open();
        Dictionary<string, string> header = string.IsNullOrEmpty(UserInfo.Token) ? null : new Dictionary<string, string>()
        {
            { "Authorization", $"Bearer {UserInfo.Token}" }
        };
        HttpRes res = await HttpHelper.PutJson(url, data, header, timeoutSeconds);
        if (showLoading) Wait.Close();
        return OnRes(res, popupError, customPopupMsgs);
    }

    private static Res OnRes(HttpRes httpRes, bool popupError, Dictionary<string, CustomPopupMsgs> customPopupMsgs)
    {
        JsonData json = httpRes.text.ToJsonData();
        if (!httpRes.success)
        {
            if (json == null)
            {
                if (popupError) Dialog.Alert($"{CommAssets.instance.I18N_network_error}\n<size=22>{httpRes.error}</size>");
                return new Res() { success = false, jsonData = json };
            }
            if ((int)json["code"] == 401)
            {
                UserInfo.OnLogout();
                LoginUI.Open();
                Dialog.Alert($"{CommAssets.instance.I18N_login_other_device}");
                return new Res() { success = false, jsonData = json };
            }
            if (json.Contains("message"))
            {
                if (popupError)
                {
                    string msg = json["message"].ToString();
                    bool hasPopup = false;
                    if (customPopupMsgs != null)
                    {
                        foreach (var customPopupMsg in customPopupMsgs)
                        {
                            if (msg.Contains(customPopupMsg.Key))
                            {
                                Dialog.Alert(customPopupMsg.Value.msg, customPopupMsg.Value.onClose);
                                hasPopup = true;
                                break;
                            }
                        }
                    }
                    if (!hasPopup) Dialog.Alert($"{CommAssets.instance.I18N_network_error}\n<size=22>{msg}</size>");
                }
            }
            else
            {
                if (popupError) Dialog.Alert($"{CommAssets.instance.I18N_network_error}\n<size=22>{httpRes.error}</size>");
            }
            return new Res() { success = false, jsonData = json };
        }
        return new Res() { success = true, jsonData = json };
    }
}
